package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.BaseRespData;
import com.cskaoyan.bean.pojo.Role;
import com.cskaoyan.bean.pojo.RoleExample;
import com.cskaoyan.bean.admin.system.*;
import com.cskaoyan.mapper.RoleMapper;
import com.cskaoyan.service.admin.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<RoleInfoOptionsVo> getRoles() {

        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andEnabledEqualTo(true);
        List<Role> roles = roleMapper.selectByExample(roleExample);
        ArrayList<RoleInfoOptionsVo> roleInfoOptionsVos = new ArrayList<>();
        for (Role role : roles) {
            RoleInfoOptionsVo roleInfoOptionsVo = new RoleInfoOptionsVo(role.getId(), role.getName());
            roleInfoOptionsVos.add(roleInfoOptionsVo);
        }

        return roleInfoOptionsVos;
    }

    @Override
    public BaseRespData queryRoleList(String name, BaseParam param) {

        PageHelper.startPage(param.getPage(), param.getLimit());

        RoleExample roleExample = new RoleExample();
        roleExample.setOrderByClause(param.getSort() + " " + param.getOrder());

        RoleExample.Criteria criteria = roleExample.createCriteria();

        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);

        List<Role> roles = roleMapper.selectByExample(roleExample);

        PageInfo<Role> rolePageInfo = new PageInfo<>(roles);

        long total = rolePageInfo.getTotal();

        return BaseRespData.create(roles, total);
    }

    @SneakyThrows
    @Override
    public RoleCreateVo createRole(RoleCreateBo roleAddBo) {

        //因为role中name属性是unique 所以首先需要判断name是否重复

        List<String> roleNames = roleMapper.selectAllName();
        for (String roleName : roleNames) {
            if (roleAddBo.getName().equals(roleName)) {
                return null;
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date datetime = sdf.parse(sdf.format(new Date()));
        String format = sdf.format(datetime);

        Role role = new Role();
        role.setId(null);
        role.setName(roleAddBo.getName());
        role.setDesc(roleAddBo.getDesc());
        role.setEnabled(true);//tinyInt
        role.setAddTime(datetime);
        role.setUpdateTime(datetime);
        role.setDeleted(false);
        int affectedRows = roleMapper.insert(role);

        //获取自增主键的id
        Integer id = role.getId();
        Role insertRole = roleMapper.selectByPrimaryKey(id);
        Date updateTime = insertRole.getUpdateTime();
        String updateTimeFormat;
        if (updateTime == null) {
            updateTimeFormat = null;
        } else {
            updateTimeFormat = sdf.format(updateTime);
        }


        RoleCreateVo roleCreateVo = new RoleCreateVo();
        roleCreateVo.setId(id);
        roleCreateVo.setName(roleAddBo.getName());
        roleCreateVo.setDesc(roleAddBo.getDesc());
        roleCreateVo.setAddTime(format);
        roleCreateVo.setUpdateTime(updateTimeFormat);

        return roleCreateVo;
    }

    @SneakyThrows
    @Override
    public int updateRole(RoleUpdateBo roleUpdateBo) {

        //仅修改描述可以允许修改,先查询一次
        Role existRole = roleMapper.selectByPrimaryKey(roleUpdateBo.getId());

        //先查重name字段
        List<String> allNames = roleMapper.selectAllName();
        for (String name : allNames) {
            if (name.equals(roleUpdateBo.getName()) && !roleUpdateBo.getName().equals(existRole.getName())) {
                return 500;
            }
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date updateDatetime = sdf.parse(sdf.format(new Date()));

        Role role = new Role();
        role.setId(roleUpdateBo.getId());
        role.setName(roleUpdateBo.getName());
        role.setDesc(roleUpdateBo.getDesc());
        role.setEnabled(true);
        role.setAddTime(sdf.parse(roleUpdateBo.getAddTime()));
        role.setUpdateTime(updateDatetime);
        role.setDeleted(false);
        int affectedRows = roleMapper.updateByPrimaryKey(role);

        if (affectedRows == 0) {
            return 404;
        }
        return 200;

    }

    @SneakyThrows
    @Override
    public int delete(RoleDeleteBo roleDeleteBo) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date updateDatetime = sdf.parse(sdf.format(new Date()));
        Role role = new Role();

        role.setId(roleDeleteBo.getId());
        role.setName(roleDeleteBo.getName());
        role.setDesc(roleDeleteBo.getDesc());
        role.setAddTime(sdf.parse(roleDeleteBo.getAddTime()));
        role.setUpdateTime(updateDatetime);
        //TODO  enable字段的作用
        role.setEnabled(false);
        role.setDeleted(true);
        int affectedRows = roleMapper.updateByPrimaryKey(role);

        return 200;
    }

    @SneakyThrows
    @Override
    public int addPermissions(PermissionsBo permissionsBo) {

        //首先将用户id和权限插入permissions表中
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date addTime = sdf.parse(sdf.format(new Date()));

        //先将原来表中roleId对应的permission的"删除"
        int affectedRows1 = roleMapper.deleteOldPermissions(permissionsBo.getRoleId());

        int affectedRows2 = roleMapper.multiInsert(permissionsBo.getRoleId(), permissionsBo.getPermissions(), addTime);

        return 0;
    }

    @Override
    public PermissonsVo getPermissions(Integer roleId) {

        PermissonsVo permissonsVo = new PermissonsVo();

        List<SystemPermissionsBean> systemPermissions = roleMapper.selectAllSystemPermissons();

        List<String> assignedPermissions = new ArrayList<>();
        if (roleId == 1) {
            //* 超级管理员  拥有所有权限
            for (SystemPermissionsBean systemPermission : systemPermissions) {
                List<ChildrenBeanX> childrenXs = systemPermission.getChildren();
                for (ChildrenBeanX childrenX : childrenXs) {
                    List<ChildBean> childrens = childrenX.getChildren();
                    for (ChildBean children : childrens) {
                        assignedPermissions.add(children.getId());
                    }
                }
            }

        } else {
            assignedPermissions = roleMapper.selectPermissionsByRoleId(roleId);
        }

        permissonsVo.setSystemPermissions(systemPermissions);
        permissonsVo.setAssignedPermissions(assignedPermissions);
        return permissonsVo;
    }


}
